import axios from 'axios'

import {BASE_URL} from './url'

import {getToken, removeToken} from './token'
const API = axios.create({
  baseURL: BASE_URL
})
// 设置请求拦截器，每次发送请求时带上token
API.interceptors.request.use(config => {
  if (config.url.startsWith('/user') && !config.url.startsWith('/user/login') && !config.url.startsWith('/user/registered')){
    config.headers.authorization = getToken()
  }
  return config
})
// 设置响应拦截器, 如果token超时，移除token
API.interceptors.response.use(response => {
  if(response.data.status === 400) {
    removeToken()
  }
  return response
})
export { API }